package com.lh.serverforwebrtc.service.impl;

import com.lh.serverforwebrtc.bean.RespBean;
import com.lh.serverforwebrtc.bean.SecurityCodeBean;
import com.lh.serverforwebrtc.bean.UserBean;
import com.lh.serverforwebrtc.mapper.SecurityCodeMapper;
import com.lh.serverforwebrtc.mapper.UserMapper;
import com.lh.serverforwebrtc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Random;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SecurityCodeMapper securityCodeMapper;

    @Override
    public RespBean getUserByPhone(Long userPhone) {
        SecurityCodeBean securityCodeBean = securityCodeMapper.queryCodeByPhone(userPhone);
        if(securityCodeBean==null){    //没有该手机号码
            Random r=new Random(System.currentTimeMillis());
            int code=(1 + r.nextInt(9)) * 100000 + r.nextInt(10000);
            SecurityCodeBean scb = new SecurityCodeBean();
            scb.setVerifiCode(code);
            scb.setPhoneNumber(userPhone);
            securityCodeMapper.insertCode(scb);
            return RespBean.success("获取验证码成功！！",code);
        }else { //已存在该手机号码
            return RespBean.success("获取验证码成功",securityCodeBean.getVerifiCode());
        }

    }

    @Override
    public RespBean updateUser(UserBean userBean) {
        UserBean uBean = userMapper.findUserById(userBean.getUserId());
        if (uBean != null){
            uBean.setUserName(userBean.getUserName());
            uBean.setUserSex(userBean.getUserSex());
            userMapper.updateUser(uBean);
            return RespBean.success("更新成功",uBean);
        }else {
            return RespBean.error("没有该用户信息，更新失败");
        }
    }

    @Override
    public UserBean getUserById(Long userId) {
        return userMapper.findUserById(userId);
    }
}
